<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/11/13
 * Time: 9:36
 */

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Model\DirectWeighting;
use App\Model\Elife;
use App\Model\Euser;
use App\Model\GroupList;
use App\Model\GroupMember;
use App\Model\Members;
use App\Model\Phone;
use App\Model\RecordList;
use App\Model\SetQuality;
use App\Model\Shareholders;
use App\Model\ShopOrder;
use App\Model\Poundage;
use App\Model\RecordBonus;
use App\Model\RecordTransaction;
use Illuminate\Http\Request;
use DB;
use Session;
use Illuminate\Console\Command;

ini_set('max_execution_time', 0);

class   CalculateController extends Controller
{
    /**
     * 股东分润计算
     */
    public function Shareholders()
    {
        $time = time();
        $newTimeH = date('H', $time);
        $newTimeI = date('i', $time);
        if ($newTimeH != 23) {
            exit('非法请求，已记录你的请求位置。');
        }
        if ($newTimeI != 59) {
            exit('非法请求，已记录你的请求位置。');
        }
        //判断是否重复
        $ShareholdersModer = new Shareholders();
        //宝砺股东分润
        $Shareholders = $ShareholdersModer->where('time', '>', time() - 86300)->where('time', '<', time())->where('type', null)->first();
        if ($Shareholders) {
            exit('失败');
        }
        //宝励股东回本率
        $bill = Poundage::where('id', 1)->value('return_rate');
        //会员列表
        $MemberModer = new Members();
        $members = $MemberModer->where(['shareholder' => 1])->where('equity_price2', '>', 0)->select(['credit1', 'credit2', 'credit3', 'credit4', 'uid', 'equity_price2', 'performance'])->get();
        $memberData = array();
        //可进行分红的股东
        foreach ($members as $k => $v) {
            if ($bill * $v['equity_price2'] > $v['performance']) {
                $memberData[] = $v;
            }
        }
        if (count($memberData) == 0) {
            exit('暂无宝砺股东参与分成');
        }
        //订单列表
        $OrderModer = new ShopOrder();
        $price = $OrderModer->where('status', '>=', 1)->where('paytime', '>', time() - 86300)->where('paytime', '<', $time)->sum('price');
        if ($price <= 0) {
            exit('no money');
        }
        //系统设置
        $PoundageModer = new  Poundage();
        $Poundage = $PoundageModer->first();
        //计算金额
        $recommend = RETAIN_TWO($price * ($Poundage['equity'] * 0.01));
        $ordersn = ORDER_SN();
        $uid = '';
        DB::beginTransaction(); //开启事务
        foreach ($memberData as $k => $v) {
            $money = RETAIN_TWO($recommend / count($memberData));
            $uid = empty($uid) ? $v['uid'] : $uid . ',' . $v['uid'];
            //扣除平台费和复投币
            if ($v['performance'] + $money > $bill * $v['equity_price2']) {
                //可分红金额
                $money = $bill * $v['equity_price2'] - $v['performance'];
                $recommendMoney = CALCULATE($Poundage, $money);
                $v['credit2'] += $recommendMoney['money'];
                $v['credit3'] += $recommendMoney['redelivery'];
                $v['performance'] += $money;
            } else {
                $money = RETAIN_TWO($recommend / count($memberData));
                $recommendMoney = CALCULATE($Poundage, $money);
                $v['credit2'] += $recommendMoney['money'];
                $v['credit3'] += $recommendMoney['redelivery'];
                $v['performance'] += $money;
            }
            //添加记录
            $this->addOrder($v['uid'], $money, 5, '股东分红', $recommendMoney, 0, $ordersn);
            //更新会员数据
            $rico = $MemberModer->where(['uid' => $v['uid']])->update($v['attributes']);
            if (empty($rico)) {
                DB::rollback();  //回滚
            }
        }
        //添加股东分红记录
        $Shareholders = new Shareholders();
        $data = [
            'uid' => $uid,
            'total' => $price,
            'people' => count($memberData),
            'money' => $money,
            'ordersn' => $ordersn,
            'time' => $time,
        ];
        $rico = $Shareholders->insert($data);
        if ($rico) {
            DB::commit();  //提交
            echo 'OK';
        }
    }

    /**
     * 内衣股东分润
     */

    public function DT_Shareholders()
    {
        $time = time();
        $newTimeH = date('H', $time);
        $newTimeI = date('i', $time);
        if ($newTimeH != 23) {
            exit('非法请求，已记录你的请求位置。');
        }
        if ($newTimeI != 58) {
            exit('非法请求，已记录你的请求位置。');
        }
        //判断是否重复
        $ShareholdersModer = new Shareholders();
        //DT内衣股东分润
        $Shareholders = $ShareholdersModer->where('time', '>', time() - 86300)->where('time', '<', time())->where('type', 1)->first();
        if ($Shareholders) {
            exit('失败');
        }
        //DT股东回本率
        $bill = Poundage::where('id', 1)->value('DT_rate');
        //会员列表
        $MemberModer = new Members();
        $members = $MemberModer->where(['DT_shareholder' => 1])->select(['credit1', 'credit2', 'credit3', 'credit4', 'uid', 'equity_price', 'DT_performance'])->get();
        $memberData = array();
        //可进行分红的股东
        foreach ($members as $k => $v) {
            if ($bill * $v['equity_price'] > $v['DT_performance']) {
                $memberData[] = $v;
            }
        }
        if (count($memberData) == 0) {
            exit('暂无DT股东参与分成');
        }
        //订单列表
        $OrderModer = new ShopOrder();
        //内衣报单总价
        $DTInvoices = $OrderModer->where('status', '>=', 1)
            ->where('paytime', '>', time() - 86300)
            ->where('paytime', '<', $time)
            ->where('mall_num', 'like', '%' . '内衣' . '%')
            ->sum('price');
        //内衣复销总价
        $DTResale = $OrderModer->join('shop_order_comment', 'shop_order_comment.orderid', '=', 'shop_order.id')
            ->where('status', '>=', 1)
            ->where('shop_order.paytime', '>', time() - 86300)
            ->where('shop_order.paytime', '<', $time)
            ->where('shop_order_comment.goodsname', 'like', '%' . '内衣' . '%')
            ->sum('shop_order.price');
        $price = $DTInvoices + $DTResale;
        if ($price <= 0) {
            exit('no money');
        }
        $PoundageModer = new  Poundage();
        $Poundage = $PoundageModer->first();
        //计算金额
        $recommend = RETAIN_TWO($price * ($Poundage['DT_equity'] * 0.01));
        $ordersn = ORDER_SN();
        $uid = '';
        DB::beginTransaction(); //开启事务
        foreach ($memberData as $k => $v) {
            $money = RETAIN_TWO($recommend / count($memberData));
            $uid = empty($uid) ? $v['uid'] : $uid . ',' . $v['uid'];
            //扣除平台费和复投币
            if ($v['DT_performance'] + $money > $bill * $v['equity_price']) {
                //可分红金额
                $money = $bill * $v['equity_price'] - $v['DT_performance'];
                $recommendMoney = CALCULATE($Poundage, $money);
                $v['credit2'] += $recommendMoney['money'];
                $v['credit3'] += $recommendMoney['redelivery'];
                $v['DT_performance'] += $money;
            } else {
                $money = RETAIN_TWO($recommend / count($memberData));
                $recommendMoney = CALCULATE($Poundage, $money);
                $v['credit2'] += $recommendMoney['money'];
                $v['credit3'] += $recommendMoney['redelivery'];
                $v['DT_performance'] += $money;
            }

            //添加记录
            $this->addOrder($v['uid'], $money, 5, 'DT内衣股东分红', $recommendMoney, 0, $ordersn);
            //更新会员数据
            $rico = $MemberModer->where(['uid' => $v['uid']])->update($v['attributes']);
            if (empty($rico)) {
                DB::rollback();  //回滚
            }
        }
        //添加股东分红记录
        $Shareholders = new Shareholders();
        $data = [
            'uid' => $uid,
            'total' => $price,
            'people' => count($memberData),
            'money' => $money,
            'type' => 1,
            'ordersn' => $ordersn,
            'time' => $time,
        ];
        $rico = $Shareholders->insert($data);
        if ($rico) {
            DB::commit();  //提交
            echo 'OK';
        }
    }


    //将宝励股东已产生的分红累计到数据库中保存
    public function performance()
    {
        echo "last";
        exit;
        $shareholdersData = Members::where('shareholder', 1)->get()->toArray();
        DB::beginTransaction(); //开启事务
        if ($shareholdersData) {
            foreach ($shareholdersData as $k => $v) {
                $bonus = RecordTransaction::where(['uid' => $v['uid'], 'explain' => '股东分红'])->sum('money');
                $res = Members::where('uid', $v['uid'])->update(['performance' => $bonus]);
                if (!$res) {
                    DB::rollback();//回滚
                    return ['code' => 0, 'data' => '修改失败'];
                }
            }
        }
        DB::commit();//提交
        return 'OK';
    }


    /**
     * 添加交易记录
     * @param null $uid 会员id
     * @param null $money 交易总金额
     * @param null $type 交易类型 1 订单 2 转账 3 提现  4充值 5 奖励制度
     * @param string $explain 交易名称
     * @param array $manageMoney 奖励金额 复投金额 平台费金额
     * @param null $company_id 公司id
     */
    public function addOrder($uid = null, $money = null, $type = null, $explain = '', $manageMoney = array(), $indirect = null, $ordersn = '')
    {
        $ordersn = empty($ordersn) ? ORDER_SN() : $ordersn;
        //交易记录表
        $order_uid = ShopOrder::where('ordersn', $ordersn)->value('uid');
        $userName = Members::where('uid', $order_uid)->value('user_name');
        $RecordTransaction = new RecordTransaction();
        //交易记录表详情表
        $RecordBonus = new RecordBonus();
        $levelinDatas = [ //交易记录
            'uid' => $uid,
            'ordersn' => $ordersn,
            'money' => $money,
            'type' => $type,
            'time' => time(),
            'explain' => $explain,
//            'company_id' => $company_id,
        ];
        $TransactionId = $RecordTransaction->add_transaction($levelinDatas);
        $bonusData = [//交易详情
            'uid' => $uid,
            'tid' => $TransactionId,
            'money' => $money,
            'remark' => $explain . '：' . $manageMoney['money'] . '，复销币：' . $manageMoney['redelivery'] . '，平台费：' . $manageMoney['platform_fee'],
//            'remark' => $explain . '：' . $money. '，分享积分来源：用户' . $userName . '参与抢购' . ',交易前分享积分'.$indirect.')',
            'time' => time(),
            'type' => 2,
//            'company_id' => $company_id,
        ];
        $RecordBonus->add_bonus($bonusData);
    }

    /**
     * 更新会员数据
     */
    public function calculate()
    {
        //会员列表
        $MemberModer = new Members();
        $date = time() - 60 * 60 * 24 * 7;
        DB::beginTransaction(); //开启事务
        $members = $MemberModer->where('sign_in', '>', (time() - 604800))->where('sign_in', '<', time())->select(['credit1', 'credit2', 'credit3', 'credit4', 'uid', 'super_recommend'])->get();
        foreach ($members as $k => $v) {
            $counts = $MemberModer->where(['referrer' => $v['uid']])->count();
            $rico = $MemberModer->where(['uid' => $v['uid']])->update(['super_recommend' => $counts]);
            if ($rico) {
                DB::rollback();  //回滚
            } else {
                DB::commit();  //提交
            }
        }

    }

    public function renewal()
    {
//        会员列表
        $MemberModer = new Members();
        DB::beginTransaction(); //开启事务
        $members = $MemberModer->where('enroll_time', '>', 1533141786)->where('straight_shop_isdown', '=', 1)->select(['credit1', 'credit2', 'credit3', 'credit4', 'performance_a', 'performance_b', 'uid', 'super_recommend'])->get();
        foreach ($members as $k => $v) {
            $this->team($v['uid']);
        }
    }

    /**
     * 团队谱首页
     */
    public function team(Request $request)
    {
//        会员列表
        $MemberModer = new Members();
//        DB::beginTransaction(); //开启事务
        $members = $MemberModer->where('enroll_time', '>', 1533141786)->where('straight_shop_isdown', '=', 1)->select(['performance_a', 'performance_b', 'uid'])->get();
//        $members = $MemberModer->where(['phone' => 18098088485])->select(['performance_a','performance_b','uid'])->get();
        foreach ($members as $k => $v) {
            $performance_a = 0;
            $performance_b = 0;
            $data = $this->subordinate($v['uid']);
            if ($data) {
                foreach ($data as $key => $val) {
                    if ($val['area'] == 'A') {
                        $performance_a = $v['performance_a'] + $val['children'];
                    } else {
                        $performance_b = $v['performance_b'] + $val['children'];
                    }
                }
                $MemberModer->where(['uid' => $v['uid']])->update(['performance_a' => $performance_a, 'performance_b' => $performance_b]);
            }

        }
    }

    //第一层
    public function subordinate($uid = null)
    {
        $MembersModel = new Members();
        $memberInfo = $MembersModel->get_members(['nodes' => $uid], ['uid', 'phone', 'name', 'user_name', 'level_name', 'nodes', 'area', 'enroll_time', 'registered', 'original_money'], null, 'area', 'asc');
        if (empty($memberInfo)) {
            return false;
        }
        foreach ($memberInfo as $k => $v) {
            $data[] = [
                'area' => $v['area'],
                'title' => $v['original_money'],
                'children' => empty($this->subordinate2($v['uid'], $v['original_money'])) ? $v['original_money'] : $this->subordinate2($v['uid'], $v['original_money'])
            ];
        }
        return $data;
    }

    //第二层
    public function subordinate2($uid = null, $original_money = null)
    {
        $MembersModel = new Members();
        $memberInfo = $MembersModel->get_members(['nodes' => $uid], ['uid', 'phone', 'name', 'user_name', 'level_name', 'nodes', 'area', 'enroll_time', 'registered', 'original_money'], null, 'area', 'asc');
        if (empty($memberInfo)) {
            return false;
        }
        $original_money1 = null;
        foreach ($memberInfo as $k => $v) {
            $original_moneys = $this->subordinate3($v['uid'], $v['original_money']);
            $original_money1 = empty($original_money1) ? $original_moneys + $v['original_money'] : $original_money1 + $original_moneys + $v['original_money'];
        }
        $data = $original_money + $original_money1;
        return $data;
    }

    //第三层
    public function subordinate3($uid = null, $original_money = null)
    {
        $MembersModel = new Members();
        $memberInfo = $MembersModel->get_members(['nodes' => $uid], ['uid', 'phone', 'name', 'user_name', 'level_name', 'nodes', 'area', 'enroll_time', 'registered', 'original_money'], null, 'area', 'asc');
        if (empty($memberInfo)) {
            return false;
        }
        $original_money2 = 0;
        foreach ($memberInfo as $k => $v) {
            $original_money2 += $v['original_money'];

        }
        return $original_money2;
    }


    /**
     * 更新会员v1团队人数数据
     * 矫正
     */
    public function GradeMembers(Request $request)
    {
        echo "没事点这个接口干嘛！";
        die;
        $startUid = $request->get('startUid');
        $endUid = $request->get('endUid');
        $members = new  Members();
        $member = $members->where('super_level', '<=', 3);
        if (!empty($startUid)) {
            $member = $member->where('uid', '>=', $startUid);
        }
        if (!empty($endUid)) {
            $member = $member->where('uid', '<=', $endUid);
        }
        $member = $member->orderBy('uid', 'desc')->select('uid', 'referrer', 'super_team_count', 'super_small_team_count', 'user_name', 'super_level')->get()->toArray();
        if (empty($member)) {
            echo "<script>alert('此段没有会员')</script>";
            echo 0;
            die;
        }
        foreach ($member as $mes => $me) {
            $numDate = [];
            $uids = [];
            $userDatas = Members::where('referrer', $me['uid'])->get(['uid', 'user_name', 'name', 'referrer'])->toArray();
            $num = 0;
            foreach ($userDatas as $key => $value) {
                $uids[0] = $value['uid'];
                $Alluser = Members::where('uid', '>', $value['uid'])->get(['referrer', 'uid'])->toArray();
                $this->PartnersNum($Alluser, $uids, 0);
                $pid = session('pid');
                $numDate[$value['uid']]['key'] = $value['uid'];
                $numDate[$value['uid']]['val'] = empty($pid) ? 1 : $pid + 1;
                $num += $numDate[$value['uid']]['val'];
            }
            //团队数量
            $num = empty($num) ? 0 : $num;
            //大小区人数
            $numDate = empty($numDate) ? 0 : $numDate;
            //推荐人数
            $count = empty($numDate) ? 0 : count($numDate);
            Members::where('uid', $me['uid'])->update(['super_recommend' => $count, 'super_team_count' => $num, 'super_small_team_count' => json_encode($numDate)]);
        }
        echo "ok";
        die;
    }


    /**
     *统计数量
     */

    public function PartnersNum($data = array(), $uid = array(), $pid = 0, $moeny = 0)
    {

        $nodesid = [];
        foreach ($data as $k => $v) {
            foreach ($uid as $key => $value) {
                if ($v['referrer'] == $value) {
//                    dump($v['original_money']);exit;
                    $pid = empty($pid) ? 1 : $pid + 1;
//                    $moeny  = empty($moeny)?$v['original_money']:$moeny+$v['original_money'];
                    $nodesid[] = $v['uid'];

                }
            }
        }
        if (!empty($nodesid)) {
            $this->PartnersNum($data, $nodesid, $pid, $moeny);
        } else {
            //保存session
            Session::put('pid', $pid);
//            Session::put('money' , $moeny);
        }
    }


    //当日累计参与抢购次数分红
    public function dayBonus()
    {

//        $time = time();
//        $newTimeH = date('H',$time);
//        $newTimeI = date('i',$time);
//        if($newTimeH != 23){
//            exit('非法请求，已记录你的请求位置。');
//        }
//        if($newTimeI != 59){
//            exit('非法请求，已记录你的请求位置。');
//        }
        //查询当日分红订单
        $lastTime = time() - 24 * 60 * 60;
//        $startTime = 1621612801;
//        $endTime = 1621699199;
        $orders = ShopOrder::where(['ordertype' => 2])->whereIn('status', [-2, 1, 2, 3])->where('createtime', '>=', $lastTime)->get()->toArray();
//        var_dump($orders);exit;
        if (empty($orders)) {
            exit('暂无分红订单');
        }
        $newOrders = [];
        $uids = [];
        //每人只计算一个订单
        foreach ($orders as $k => $v) {
            if (!in_array($v['uid'], $uids)) {
                $newOrders[] = $v;
                $uids[] = $v['uid'];
            }
        }
//        var_dump($orders);die;
        //会员列表
        $MemberModer = new Members();
        $members = $MemberModer->where('numbers', '>', 0)->select(['uid', 'credit1', 'numbers'])->get()->toArray();
//        var_dump($members);exit;
        if (count($members) < 1) {
            exit('暂无参与活动人员');
        }
        //系统设置
        $DirectWeightingModer = new  DirectWeighting();
        $PoundageData = $DirectWeightingModer->get()->toArray();
        $order = ORDER_SN();
        $PoundageModer = new  Poundage();
        $Poundage = $PoundageModer->first();
        DB::beginTransaction(); //开启事务
        foreach ($newOrders as $k => $v) {
            $user = Members::where('uid', $v['uid'])->first();
            //直推人奖励（分享奖）
            $direct = Members::where('uid', $user['referrer'])->first();
            if ($direct && $direct['numbers'] > 0) {
                if ($direct['numbers'] >= $PoundageData[0]['start'] && $direct['numbers'] <= $PoundageData[0]['end']) {
                    $money1 = $PoundageData[0]['rebate'] * $user['numbers'];
                } else if ($direct['numbers'] >= $PoundageData[1]['start'] && $direct['numbers'] <= $PoundageData[1]['end']) {
                    $money1 = $PoundageData[1]['rebate'] * $user['numbers'];
                } else {
                    $money1 = $PoundageData[2]['rebate'] * $user['numbers'];
                }
                $recommendMoney = ['money' => $money1, 'redelivery' => 0];
                $this->credit2Record($direct['uid'], $v['ordersn']);
                //添加到余额
                $rico = Members::where('uid', $direct['uid'])->update([
                    'credit5' => $direct['credit5'] + $recommendMoney['money'],
//                'credit5' => $direct['credit5'] + $recommendMoney['redelivery']
                ]);
                if ($rico) {
                    $this->addOrder($direct['uid'], $money1, 5, '抢购直推分享积分', $recommendMoney, $direct['credit5'], $v['ordersn']);
//                        $this->team_achievement($direct['uid'],$money1);
                }

            }
            //间接推荐人（管理奖）
            $indirect = Members::where('uid', $direct['referrer'])->first();
            if ($indirect['numbers'] > 0) {
                $money2 = 10 * $user['numbers'];
                $recommendMoney = ['money' => $money2, 'redelivery' => 0];
                $this->credit2Record($indirect['uid'], $v['ordersn']);
                //添加到余额
                $rico = Members::where('uid', $indirect['uid'])->update([
                    'credit5' => $indirect['credit5'] + $recommendMoney['money'],
//                    'credit5' => $direct['credit5'] + $recommendMoney['redelivery']
                ]);
                if ($rico) {
//                            $this->bonusCredit2($indirect['uid'], $v['ordersn']);
                    $this->addOrder($indirect['uid'], $money2, 5, '抢购间接分享积分', $recommendMoney, $indirect['credit5'], $v['ordersn']);
//                            $this->achievement($indirect['uid'],$money2);
                }
            }
//                foreach ($PoundageData as $key => $val) {
//                    if ($v['day_times'] >= $val['start'] && $v['day_times'] <= $val['end']) {
//                        $recommendMoney = CALCULATE($Poundage,$val['rebate'],9);
//                        $v['credit1'] += $val['rebate'];
//                        //记录订单之前各会员的奖励币余额记录
//                        $this->credit2Record($ordersn, $v['uid']);
//                        $v['addData']['addData1']['money'] = $val['rebate'];
//                        $v['addData']['addData1']['type'] = 9;
//                        $v['addData']['addData1']['text'] = '当日参与活动额外奖励';
//                        $v['addData']['addData2']['recommendMoney'] = $recommendMoney;
//                        $v['addData']['addData1']['company_id'] = 1;
//                        $v['addData']['addData1']['ordersn'] = $ordersn;
//                    }
//                }
//                if($MemberModer->where(['uid' => $v['uid']])->update([
//                    'credit1' =>$v['credit1'],
//                    'day_times' =>0  //这里是执行成功的 但是没有改数据
//                ])){
//                    $this->addOrder($v['uid'], $v['addData']['addData1']['money'], 9, $v['addData']['addData1']['text'],$v['addData']['addData2']['recommendMoney'],$v['addData']['addData1']['company_id'], $v['addData']['addData1']['ordersn']);
//                }

        }
//        //添加股东分红记录
//        $Shareholders = new Shareholders();
//        $data = [
//            'uid' => $uid,
//            'total' => $price,
//            'people' => count($memberData),
//            'money' => $money,
//            'ordersn' => $ordersn,
//            'time' => $time,
//        ];
//        $rico = $Shareholders->insert($data);
//        if($rico){
        DB::commit();  //提交
        echo 'OK';
//        }

    }

    /**
     * 记录订单之前各会员的奖励币余额记录
     * @param int $uid 用户ID
     * @param string $ordersn 统一订单
     * @return array
     */
    public function credit2Record($ordersn, $uid)
    {
        $ShopOrder = new ShopOrder();
        $UserModel = new Members();
        $orderMemberCredit2Datas = [];
        $orderMemberCredit2Uid = [];
        $orderMemberCredit2Uids = [];
        $memberLastCredit2Data = $ShopOrder->where(['ordersn' => $ordersn])->value('last_credit2s');
        if ($memberLastCredit2Data != "") {
            $memberLastCredit2Data = unserialize($memberLastCredit2Data);
        } else {
            $memberLastCredit2Data = [];
        }
        $memberLastCredit2 = [];
        $memberLastData = $UserModel->where(['uid' => $uid])->select('uid', 'name', 'user_name', 'credit1', 'credit2', 'credit5', 'voucher')->first();
        $memberLastCredit2['uid'] = $memberLastData['uid'];
        $memberLastCredit2['name'] = $memberLastData['name'];
        $memberLastCredit2['user_name'] = $memberLastData['user_name'];
        $memberLastCredit2['credit1'] = $memberLastData['credit1'];
        $memberLastCredit2['credit2'] = $memberLastData['credit2'];
        $memberLastCredit2['credit5'] = $memberLastData['credit5'];
        $memberLastCredit2['voucher'] = $memberLastData['voucher'];
        if ($memberLastCredit2Data) {
            foreach ($memberLastCredit2Data as $key => $value) {
                array_push($orderMemberCredit2Uid, $value['uid']);
            }
            if (!in_array($uid, $orderMemberCredit2Uid)) {
                array_push($memberLastCredit2Data, $memberLastCredit2);
            }
            $Credit2SaveData = serialize($memberLastCredit2Data);
        } else {
            if (count($orderMemberCredit2Datas) > 0) {
                foreach ($orderMemberCredit2Datas as $key => $value) {
                    array_push($orderMemberCredit2Uids, $value['uid']);
                }
                if (!in_array($uid, $orderMemberCredit2Uids)) {
                    array_push($orderMemberCredit2Datas, $memberLastCredit2);
                }
            } else {
                array_push($orderMemberCredit2Datas, $memberLastCredit2);
            }
            $Credit2SaveData = serialize($orderMemberCredit2Datas);
        }
        $ShopOrder->where(['ordersn' => $ordersn])->update(['last_credit2s' => $Credit2SaveData]);
    }

    /**
     * 定时任务清楚会员新增数量
     */
    public function clear()
    {
        //        $time = time();
//        $newTimeH = date('H',$time);
//        $newTimeI = date('i',$time);
//        if($newTimeH != 23){
//            exit('非法请求，已记录你的请求位置。');
//        }
//        if($newTimeI != 59){
//            exit('非法请求，已记录你的请求位置。');
//        }
        //会员列表
        //会员列表
        $PhoneModer = new Phone();
        $members = $PhoneModer->get()->toArray();
        foreach ($members as $v) {
            preg_match('/\d+/', $v['name'], $res);
            foreach ($res as $value) {
                $phone = substr($value, 0, 6);
                $rows = $PhoneModer->where('id', $v['id'])->update(['phone' => $v['phone'] . $phone]);
            }


        }
        if ($rows) {
            echo 'OK';
        }

    }

    /**
     * 团购订单退回
     */
    public function return_order()
    {
        $time = time();
//        $newTimeH = date('H',$time);
        $newTimeI = date('i', $time);
//        if($newTimeH != 23){
//            exit('非法请求，已记录你的请求位置。');
//        }
//        if($newTimeI != 59 || $newTimeI != 29){
//            exit('非法请求，已记录你的请求位置。');
//        }

//        $redis = new \redis();
//        $redis->connect('127.0.0.1', 6379);
        $groupModel = new GroupList();
        $groupmemberModel = new GroupMember();
        $lastTime = time() - 60 * 5;
        $lists = $groupModel->where('createtime', '<=', $lastTime)->where('open_state', 0)->get()->toArray();
//        $lists = $groupModel->where('open_state',0)->get()->toArray();
        foreach ($lists as $k => $v) {
            $orders = $groupmemberModel->where('bid', $v['id'])->get()->toArray();
//            file_put_contents('./calculate/'.$v['id'].'order.txt',print_r($orders,true).PHP_EOL,FILE_APPEND);
            foreach ($orders as $key => $value) {
                $order = ShopOrder::where('id', $value['order_id'])->first();
                $user = Members::where('uid', $value['uid'])->first();
                $res = Members::where('uid', $value['uid'])->update(['credit1' => $user['credit1'] + $order['price']]);
                //添加退款记录
                if ($res) {
                    $recommendMoney = $order['price'];
//                    $recommendMoney['redelivery'] = 0;
//                    $recommendMoney['platform_fee'] = 0;
//                    $ordersn = $order['ordersn'];
                    //交易记录表
                    $RecordTransaction = new RecordTransaction();
                    //交易记录表详情表
                    $RecordBonus = new RecordBonus();
                    $levelinDatas = [ //交易记录
                        'uid' => $order['uid'],
                        'ordersn' => $order['ordersn'],
                        'money' => $recommendMoney,
                        'type' => 7,
                        'time' => time(),
                        'explain' => '开团失败积分退还',
                        'company_id' => 0,
                    ];
                    $TransactionId = $RecordTransaction->add_transaction($levelinDatas);
                    ShopOrder::where('id', $value['order_id'])->update(['status' => -1]);
//                    file_put_contents('./calculate/'.$value['order_id'].'sql.txt',ShopOrder::getQueryLog().PHP_EOL,FILE_APPEND);
                }
            }
//            $redis->lpush('goods_'.$v['group_id'],$redis->hGet('order_info',$v['uid']));
            //修改团购状态
            GroupList::where('id', $v['id'])->update(['open_state' => -1]);
        }
        return 'OK';

    }

    /**
     * 直推奖励业绩累计
     * @param $uid
     * @param $money
     * @return bool
     */
    public function team_achievement($uid, $money)
    {
        $user = Members::where('uid', $uid)->first();
        //累计业绩
        Members::where('uid', $uid)->update([
            'team_achievement' => $user['team_achievement'] + $money,
            'achievement_increment' => $user['achievement_increment'] + $money,
            'team_numbers' => $user['team_numbers'] + 1
        ]);
        //查询是否有推荐人
        $referrer = Members::where('uid', $user['referrer'])->first();
        if (empty($referrer)) {
            return true;
        } else {
            return $this->team_achievement($user['referrer'], $money);
        }

    }

    /**
     * 间推奖励业绩累计
     * @param $uid
     * @param $money
     * @return bool
     */
    public function achievement($uid, $money)
    {
        $user = Members::where('uid', $uid)->first();
        //累计业绩
        Members::where('uid', $uid)->update([
            'team_achievement' => $user['team_achievement'] + $money,
            'achievement_increment' => $user['achievement_increment'] + $money,
        ]);
        //查询是否有推荐人
        $referrer = Members::where('uid', $user['referrer'])->first();
        if (empty($referrer)) {
            return true;
        } else {
            return $this->achievement($user['referrer'], $money);
        }

    }

    /**
     * @param $uid
     * 统计个人及团队累计数据
     */
    public function statistics($uid)
    {
        $othersUid = array();
        $team = array();
        $othersUid[] = $uid;
        $teamAchievement = 0;
        $times = 0;
        $achievement_increment = 0;
        do {
            $memberList = Members::whereIn('referrer', $othersUid)->select('uid', 'referrer')->get()->toArray();
            if ($memberList) {
                unset($othersUid);
                foreach ($memberList as $k => $v) {
                    $team[] = $v['uid'];
                    $othersUid[] = $v['uid'];
                }
            }
        } while (empty($othersUid));
        if (!empty($team)) {
            foreach ($team as $k => $v) {
                $user = Members::where('uid', $v['uid'])->select('single_achievement', 'day_times', 'day_achievement')->first();
                $teamAchievement += $user['single_achievement'];//团队业绩
                $times += $user['day_times'];//团队参与局数
                $achievement_increment += $user['day_achievement'];//团队新增业绩
            }
            $res = Members::where('uid', $uid)->update(['team_achievement' => $teamAchievement, 'team_numbers' => $times, 'achievement_increment' => $achievement_increment]);
            if ($res) {
                return ['code' => 1, 'data' => '统计个人业绩成功'];
            } else {
                return ['code' => 0, 'data' => '统计失败'];
            }
        } else {
            return ['code' => 0, 'data' => '暂无个人团队'];
        }


    }

    public function setNumbers()
    {

        $times = time() - 24 * 60 * 60;
        $memberModel = new Members();
        $members = $memberModel->get()->toArray();
        $update = array();
        foreach ($members as $k => $v) {
            $uid = $v['uid'];
            $update['day_times'] = ShopOrder::where('uid', $uid)->whereIn('status', [-2, 1])->count();

            $update['single_achievement'] = ShopOrder::where('uid', $uid)->where('status', 1)->sum('price');

            $update['numbers'] = ShopOrder::where('uid', $uid)->whereIn('status', [-2, 1])->where('createtime', '>', $times)->count();

            $update['day_achievement'] = ShopOrder::where('uid', $uid)->where('status', 1)->where('createtime', '>', $times)->sum('price');
            $update['day_probability'] = ShopOrder::where('uid', $uid)->where('status', 1)->count();

            $rico = $memberModel->where('uid', $v['uid'])->update($update);

        }
    }

    /**
     * 定时当日订单当日订单消费分红
     */
    public function clearBonus()
    {
        $time = time();
        $newTimeH = date('H', $time);
        $newTimeI = date('i', $time);
        if ($newTimeH != 23) {
            exit('非法请求，已记录你的请求位置。');
        }
        if ($newTimeI != 56) {
            exit('非法请求，已记录你的请求位置。');
        }
        $poundageModel = new Poundage();
        //会员列表
        $MemberModer = new Members();
        $res = $poundageModel->where('id', 1)->update(['subsidy_reward' => 0]);
        $members = $MemberModer->where('is_read', 1)->get();
        foreach ($members as $k => $v) {
            $MemberModer->where(['uid' => $v['uid']])->update(['is_read' => 0]);
        }
        if ($res) {
            echo 'OK';
        }

    }

    /*
   * 定时分红
   */
    public function operate()
    {
        $time = time();
        $newTimeH = date('H', $time);
        $newTimeI = date('i', $time);
        if ($newTimeH != 23) {
            exit('非法请求，已记录你的请求位置。');
        }
        if ($newTimeI != 50) {
            exit('非法请求，已记录你的请求位置。');
        }
        $PoundageModel = new Poundage();
        $Poundage = $PoundageModel->first();

        $beginToday = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
        $endToday = mktime(23, 59, 58, date('m'), date('d'), date('Y'));
        $record = RecordList::where('time', '>=', $beginToday)->where('time', '<=', $endToday)->where('status', '=', 0)->first();
        if ($record) {
            $UserModel = new Members();
            $members = $UserModel->where('voucher', '>', '0')->where('platform_profit', 1)->get()->toArray();
            foreach ($members as $k => $v) {
//                if ($v['consumption_bonus'] > 990 * 2) {
//                    //分红上限
//                    $results = $UserModel->where('uid', $v['uid'])->update(['is_out' => 0, 'voucher' => 0, 'consumption_bonus' => 0]);
//                    $RecordTransaction = new RecordTransaction();
//                    if ($results) {
//                        $recommendData = [
//                            'uid' => $v['uid'],
//                            'ordersn' => $record['bonus_sn'],
//                            'money' => 0,
//                            'type' => 1,
//                            'time' => time(),
//                            'explain' => '已出局',
//                            'remark' => '已出局',
//                        ];
//                        $RecordTransaction->add_transaction($recommendData);
//                    } else {
//                        return ['code' => 0, 'data' => '分红失败'];
//                    }
//                    unset($members[$k]);
//                }
                $money2 = RETAIN_TWO($record['single'] * $v['voucher']);
                $recommendMoney = CALCULATD($Poundage, $money2, 2);
                //添加记录
                $v['credit2'] += $recommendMoney['money'];
                $v['credit5'] += $recommendMoney['redelivery'];
                $v['consumption_bonus'] += $money2;
                $v['achievement_increment'] = 0;
                //记录订单之前各会员的奖励币余额记录
                $res = $UserModel->where('uid', $v['uid'])->update(['achievement_increment' => 0, 'credit2' => $v['credit2'], 'credit5' => $v['credit5'], 'consumption_bonus' => $v['consumption_bonus']]);
                //重新赋值
                $addData3['money'] = $money2;
                $addData3['type'] = 5;
                $addData3['text'] = $record['remark'];
                $addData3['remark'] = 2;
                $addData3['recommendMoney'] = $recommendMoney;
                $addData3['ordersn'] = $record['bonus_sn'];
                if ($res) {
                    $this->addOrder($v['uid'], $addData3['money'], 5, $addData3['text'], $addData3['recommendMoney'], 0, $addData3['ordersn'], $addData3['remark']);
                }
            }
            //修改记录状态
            $res = [
                'status' => 1,
                'updated_at' => date('Y-m-d H:i', time())
            ];
            $rico = RecordList::where('id', $record['id'])->update($res);
            if ($rico) {
                echo 'OK';
            } else {
                echo 'error';
            }

        } else {
            echo 'error1';
        }
    }

    /**
     * 会员导入
     */
//    public function import_member()
//    {
//        $name = '18800000311';
//        $memberModel = new Members();
//        $user = Euser::where('referrer', $name)->get()->toArray();
////        print_r($user);exit;
//        foreach ($user as $value) {
//            $referrer = $memberModel->where('name', $name)->first();
//            $memberData = array();
//            $memberData['user_name'] = $value['name'];
//            $memberData['phone'] = $value['mobile'];
//            //密码加密
//            $passRand = RANDOM();
//            $memberData['salting'] = $passRand;
//            $memberData['password'] = ENCRYPTION($value['mobile'], $passRand);
//            //设置默认账号
//            $memberData['name'] = $value['mobile'];
//            //设置分享人ID
//            $memberData['referrer'] = $referrer['uid'];
//            //设置分享人姓名
//            $memberData['feferrer_name'] = $referrer['user_name'];
//            //注册时间
//            $memberData['enroll_time'] = time();
//            //直商城开关 1开 2关
//            $memberData['straight_shop_isdown'] = 2;
////            //超级商城开关 1开 2关
////            $memberData['isdown'] = $referrerInfo['isdown'];
//            //支付密码随机数
//            $memberData['salting_pay'] = $passRand;
//            //默认支付密码
//            $memberData['password_pay'] = ENCRYPTION($value['mobile'], $passRand);
//            //激活时间
//            $memberData['activation_time'] = time();
//
//            $memberData['registered'] = 1; //1 已激活 0 未激活
//            $memberData['is_withdraw'] = 1;//0 禁止提现 1 允许
//            $memberData['is_shift'] = 1;   //0 禁止转账 1 允许
//            $memberData['voucher'] = 1;   //0 默认份额 1
//            $memberData['super_level'] = 1;   //报单商城等级
//            $rico = $memberModel->insertGetId($memberData);
//            //业绩设置
//            $QualityModel = new SetQuality();
//            $Quality = $QualityModel->get()->toArray();
//            $puid = $rico;
//            $arrays = [];
//            $share = $referrer = $memberData['referrer'];
//            $members = $memberModel->where('uid', '<=', $rico)->orderBy('uid', 'desc')->select('uid', 'referrer', 'level', 'level_name', 'level_grade', 'credit1', 'credit2', 'credit3', 'credit4', 'credit5', 'team_member_count', 'super_recommend', 'super_team_count', 'super_small_team_count', 'super_level', 'super_level_name', 'is_credit3', 'type', 'achievement', 'team_profit')->get()->toArray();
//            foreach ($members as $k => $v) {
//                if (!empty($v['referrer'])) {
//                    if ($referrer == $v['uid']) {    //寻找上级id 微客
//                        $referrer = $v['referrer'];
//                        $arrays[$v['uid']] = $v['referrer'];
//                        $v = $this->UpGrade($v, $puid, $Quality, $arrays, $share, 0);
//                        //上级uid
//                        $puid = $v['uid'];
//                        //更新会员数据
//                        $memberModel->where(['uid' => $v['uid']])->update(
//                            [
//                                'credit1' => $v['credit1'],
//                                'credit2' => $v['credit2'],
//                                'credit3' => $v['credit3'],
//                                'credit4' => $v['credit4'],
//                                'credit5' => $v['credit5'],
//                                'level' => $v['level'],
//                                'level_name' => $v['level_name'],
//                                'level_grade' => $v['level_grade'],
//                                'super_recommend' => $v['super_recommend'],
//                                'team_member_count' => $v['team_member_count'],
//                                'super_team_count' => $v['super_team_count'],
//                                'super_small_team_count' => $v['super_small_team_count'],
//                            ]);
//                    }
//                }
//
//            }
//        }
//    }

    public function UpGrade($v, $puid, $Quality, $array = array(), $share, $points)
    {
        $v['super_team_count'] += $points;
        $v['team_member_count'] += 1;
        //添加小区团队
        $super_small_team_count = json_decode($v['super_small_team_count'], true);
        if ($super_small_team_count) {  //判断是否已有团队业绩
            foreach ($super_small_team_count as $items => $item) {
                if ($share == $v['uid']) {//判断是否已有这个会员的业绩
                    $super_small_team_count[$puid] = [
                        'key' => $puid,
                        'val' => 1,
                        'money' => $points,
                    ];

                }
                if (isset($array[$items]) ? $array[$items] : 0) {
                    $super_small_team_count[$items]['money'] += $points;
                    $super_small_team_count[$items]['val'] += 1;
                }
            }
            $super_small_team_count = json_encode($super_small_team_count);

        } else {
            $team_count = [
                $puid => [
                    'key' => $puid,
                    'val' => 1,
                    'money' => $points,
                ]
            ];

            $super_small_team_count = json_encode($team_count);
        }
        $v['super_small_team_count'] = $super_small_team_count; //添加小区团队
        /*--------------------------------------**/
        //直推人数查询
        $realTeamCount = Members::where(['referrer' => $v['uid']])->select('uid')->count();
        $v['super_recommend'] = $realTeamCount;
        if ($v['level'] == 0) {  //v1
            if ($v['achievement'] >= $Quality[0]['consumption']) {
                $v['level_name'] = $Quality[0]['level_name'];
                $v['level'] = $Quality[0]['level'];
                $v['level_grade'] = $Quality[0]['level_stage'];
            }
        }

        if ($v['level'] == 1 && $v['level_grade'] == 1) {
            $super_small_team_count = json_decode($v['super_small_team_count'], true);
            if ($super_small_team_count) {
                //重组数组
                $arrSort = array();
                foreach ($super_small_team_count as $uniqid => $row) {
                    foreach ($row as $key => $value) {
                        $arrSort[$key][$uniqid] = $value;
                    }
                }
                //排序 倒序
                array_multisort($arrSort['money'], constant('SORT_DESC'), $super_small_team_count);
                $counts = 0; //小区人数
                $big_num = 0; //大区人数
                foreach ($super_small_team_count as $items => $item) {
                    //计算大小区
                    if ($big_num > 0) {
                        $counts += $item['money'];
                    } else {
                        $big_num = $item['money'];
                    }
                }
                if ($v['super_team_count'] >= $Quality[1]['team_count'] && $v['achievement'] >= $Quality[1]['consumption']) {
                    $v['level_grade'] = $Quality[1]['level_stage'];
                }
            }

        }

        if ($v['level'] == 1 && $v['level_grade'] == 2) {
            $super_small_team_count = json_decode($v['super_small_team_count'], true);
            if ($super_small_team_count) {
                //重组数组
                $arrSort = array();
                foreach ($super_small_team_count as $uniqid => $row) {
                    foreach ($row as $key => $value) {
                        $arrSort[$key][$uniqid] = $value;
                    }
                }
                //排序 倒序
                array_multisort($arrSort['money'], constant('SORT_DESC'), $super_small_team_count);
                $counts = 0; //小区人数
                $big_num = 0; //大区人数
                foreach ($super_small_team_count as $items => $item) {
                    //计算大小区
                    if ($big_num > 0) {
                        $counts += $item['money'];
                    } else {
                        $big_num = $item['money'];
                    }
                }
                if ($v['super_team_count'] >= $Quality[2]['team_count'] && $v['achievement'] >= $Quality[2]['consumption']) {
                    $v['level_grade'] = $Quality[2]['level_stage'];
                }
            }

        }

        if ($v['level'] == 1 && $v['level_grade'] == 3) {
            $super_small_team_count = json_decode($v['super_small_team_count'], true);
            if ($super_small_team_count) {
                //重组数组
                $arrSort = array();
                foreach ($super_small_team_count as $uniqid => $row) {
                    foreach ($row as $key => $value) {
                        $arrSort[$key][$uniqid] = $value;
                    }
                }
                //排序 倒序
                array_multisort($arrSort['money'], constant('SORT_DESC'), $super_small_team_count);
                $counts = 0; //小区人数
                $big_num = 0; //大区人数
                foreach ($super_small_team_count as $items => $item) {
                    //计算大小区
                    if ($big_num > 0) {
                        $counts += $item['money'];
                    } else {
                        $big_num = $item['money'];
                    }
                }
                if ($v['super_team_count'] >= $Quality[3]['team_count'] && $v['achievement'] >= $Quality[3]['consumption']) {
                    $v['level_grade'] = $Quality[3]['level_stage'];
                }
            }
        }

        if ($v['level'] == 1 && $v['level_grade'] == 4) {
            $super_small_team_count = json_decode($v['super_small_team_count'], true);
            if ($super_small_team_count) {
                //重组数组
                $arrSort = array();
                foreach ($super_small_team_count as $uniqid => $row) {
                    foreach ($row as $key => $value) {
                        $arrSort[$key][$uniqid] = $value;
                    }
                }
                //排序 倒序
                array_multisort($arrSort['money'], constant('SORT_DESC'), $super_small_team_count);
                $counts = 0; //小区人数
                $big_num = 0; //大区人数
                foreach ($super_small_team_count as $items => $item) {
                    //计算大小区
                    if ($big_num > 0) {
                        $counts += $item['money'];
                    } else {
                        $big_num = $item['money'];
                    }
                }
                if ($v['super_team_count'] >= $Quality[4]['team_count'] && $v['achievement'] >= $Quality[4]['consumption']) {
                    $v['level_name'] = $Quality[4]['level_name'];
                    $v['level'] = $Quality[4]['level'];
                    $v['level_grade'] = $Quality[4]['level_stage'];
                }
            }
        }

        if ($v['level'] == 2 && $v['level_grade'] == 1) {
            $super_small_team_count = json_decode($v['super_small_team_count'], true);
            if ($super_small_team_count) {
                //重组数组
                $arrSort = array();
                foreach ($super_small_team_count as $uniqid => $row) {
                    foreach ($row as $key => $value) {
                        $arrSort[$key][$uniqid] = $value;
                    }
                }
                //排序 倒序
                array_multisort($arrSort['money'], constant('SORT_DESC'), $super_small_team_count);
                $counts = 0; //小区人数
                $big_num = 0; //大区人数
                foreach ($super_small_team_count as $items => $item) {
                    //计算大小区
                    if ($big_num > 0) {
                        $counts += $item['money'];
                    } else {
                        $big_num = $item['money'];
                    }
                }
                if ($counts >= $Quality[5]['small_team_count'] && $v['achievement'] >= $Quality[5]['consumption']) {
                    $v['level_grade'] = $Quality[5]['level_stage'];
                }
            }
        }

        if ($v['level'] == 2 && $v['level_grade'] == 2) {
            $super_small_team_count = json_decode($v['super_small_team_count'], true);
            if ($super_small_team_count) {
                //重组数组
                $arrSort = array();
                foreach ($super_small_team_count as $uniqid => $row) {
                    foreach ($row as $key => $value) {
                        $arrSort[$key][$uniqid] = $value;
                    }
                }
                //排序 倒序
                array_multisort($arrSort['money'], constant('SORT_DESC'), $super_small_team_count);
                $counts = 0; //小区人数
                $big_num = 0; //大区人数
                foreach ($super_small_team_count as $items => $item) {
                    //计算大小区
                    if ($big_num > 0) {
                        $counts += $item['money'];
                    } else {
                        $big_num = $item['money'];
                    }
                }
                if ($counts >= $Quality[6]['small_team_count'] && $v['achievement'] >= $Quality[6]['consumption']) {
                    $v['level_name'] = $Quality[6]['level_name'];
                    $v['level'] = $Quality[6]['level'];
                    $v['level_grade'] = $Quality[6]['level_stage'];
                }
            }
        }
        return $v;
    }

    /**
     * 处理数据
     */
    public function import_member()
    {


        $member = Members::where('is_read',0)->get()->toArray();
//        $members = array_unique($member);
//        var_dump($members);exit;

        foreach ($member as $v) {
            $data = Elife::where('ids', $v['original_id'])->first();
            if ($data) {
                $passRand = RANDOM();
                $user = [
//                    //密码加密
//
//            $memberData['salting'] = $passRand;
//            $memberData['password'] = ENCRYPTION($value['mobile'], $passRand);
//
//            //支付密码随机数
//            $memberData['salting_pay'] = $passRand;
//            //默认支付密码
//            $memberData['password_pay'] = ENCRYPTION($value['mobile'], $passRand);
                    'user_name' => $data['name'],
                    'salting' => $passRand,
                    'password' => ENCRYPTION($data['mobile'], $passRand),
                    'salting_pay' => $passRand,
                    'password_pay' =>ENCRYPTION($data['mobile'], $passRand),
                    'phone' => $data['mobile'],
                    'name' => $data['mobile'],
//                    'achievement' => $data['reg_jb'],

                ];
                Members::where('original_id', $v['original_id'])->update($user);
            }
        }

    }
}
